﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BusLib
{
    public partial class Calendar
    {
        public static TimeSpan FirstTripOfTheDay = TimeSpan.FromHours(4); // 4 am

        public static List<Calendar> GetActiveService(DateTime t)
        {
            DateTime serviceDay = (t - Calendar.FirstTripOfTheDay).Date;
            DayOfWeek day = serviceDay.DayOfWeek;
            
            return BusLibDataContext.db.Calendars.Where(
                c => c.start_date < t
                && c.end_date > t
                && (day != DayOfWeek.Sunday || c.sunday)
                && (day != DayOfWeek.Monday || c.monday)
                && (day != DayOfWeek.Tuesday || c.tuesday)
                && (day != DayOfWeek.Wednesday || c.wednesday)
                && (day != DayOfWeek.Thursday || c.thursday)
                && (day != DayOfWeek.Friday || c.friday)
                && (day != DayOfWeek.Saturday || c.saturday)
                && !c.Calendar_Dates.Any(cd => cd.date == serviceDay && cd.exception_type == 2)
                ).Union(BusLibDataContext.db.Calendars.Where(
                    c => c.Calendar_Dates.Any(cd => cd.date == serviceDay && cd.exception_type == 1)))
                .ToList();
        }


        internal static DateTime parseDate(string s)
        {
            s = s.Insert(6, "/");
            s = s.Insert(4, "/");

            return DateTime.Parse(s) + FirstTripOfTheDay;
        }

        public static Calendar ImportCSV(string line)
        {
            Calendar c = null;
            string[] fields = line.Split(',');

            if (fields[0] != "service_id")
            {
                c = new Calendar();
                c.service_id = fields[0];
                c.monday = int.Parse(fields[1]) == 1;
                c.tuesday = int.Parse(fields[2]) == 1;
                c.wednesday = int.Parse(fields[3]) == 1;
                c.thursday = int.Parse(fields[4]) == 1;
                c.friday = int.Parse(fields[5]) == 1;
                c.saturday = int.Parse(fields[6]) == 1;
                c.sunday = int.Parse(fields[7]) == 1;
                c.start_date = parseDate(fields[8]);
                c.end_date = parseDate(fields[9]) - TimeSpan.FromSeconds(1);  // 3:59 am
                BusLibDataContext.db.Calendars.InsertOnSubmit(c);
            }
            return c;
        }
    }
}
